package com.yc.common.handler;

import com.alibaba.fastjson.JSON;
import com.yc.common.utils.ServletUtil;
import com.yc.entity.WxUser;
import com.yc.exception.WxLoginException;
import com.yc.vo.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 配置微信访问全局拦截器
 * @author mqm
 * @version 1.0
 * @date 2023/7/7 17:10
 */
public class WxInterceptor implements HandlerInterceptor {

    @Resource
    private WxUser wxUser;
    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            String username = wxUser.getUsername();
            Object wxlogin = redisTemplate.opsForHash().get("WXSESSIONKEY::"+username, "session_key");
            Long expire = redisTemplate.getExpire("WXSESSIONKEY::"+username);
            if (0<expire&&expire<10800){
                redisTemplate.expire("WXSESSIONKEY::" + username, 66, TimeUnit.HOURS);
            }
            if (expire<=0||wxlogin==null){
                Result error = Result.error(2,"登录超时!");
                ServletUtil.write(JSON.toJSONString(error));
                return false;
            }else {
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new WxLoginException("请您先登录!",2);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
